package com.ftj.bills.sys.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ftj.bills.common.ResultObj;
import com.ftj.bills.sys.pojo.User;
import com.ftj.bills.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 21seu.ftj
 */
@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/")
    public String toLoginPage() {
        return "login";
    }

    @RequestMapping("/login")
    @ResponseBody
    public ResultObj login(String loginname, String pwd, String code, HttpSession session) {
        Object codeSession = session.getAttribute("code");
        if (codeSession != null && code.equals(codeSession)) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("loginname", loginname);
            queryWrapper.eq("pwd", pwd);
            User user = userService.getOne(queryWrapper);
            if (user != null) {
                session.setAttribute("user", user);
                return new ResultObj(200, "登录成功！");
            } else {
                return new ResultObj(-1, "用户名或密码不正确！");
            }
        } else {
            return new ResultObj(-1, "验证码错误！");
        }
    }

    @RequestMapping("/login/getCode")
    public void getCode(HttpServletResponse response, HttpSession session) throws IOException {
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(116, 36, 4, 5);
        String code = circleCaptcha.getCode();
        System.out.println(code);
        session.setAttribute("code", code);
        ServletOutputStream os = response.getOutputStream();
        circleCaptcha.write(os);
        os.close();
    }
}
